import {Button, message, Tag, Row, Col} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DetailsForm from './components/DetailsForm';
import {getRoleList, queryRule, removeRule, sysncu, updateUser} from './service';
import './monitor.less'
// import {PlusOutlined} from "@ant-design/icons";


/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      idList: selectedRows.map(row => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async fields => {
  const hide = message.loading('正在更新');
  try {
    await updateUser(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

const TableList = () => {
  const actionRef = useRef();
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [selectedRowsState, setSelectedRows] = useState([]);

  const [options, setOptions] = useState([]);
  /**
   * 用户同步
   * @returns {Promise<boolean>}
   */
  const  handleAccountSysnc = async () =>{
    const hide = message.loading('正在同步');
    try{
      await sysncu();
      hide();
      message.success('账号同步成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    }catch (e) {
      hide();
      message.error('账号同步失败请重试！');
      return false;
    }
  };



  useEffect(() => {
    getRoleList().then(res => {
      if (res.status === 200) {
        setOptions(res.data);
      }
    });
  }, []);

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      sorter: true
    },
    {
      title: '用户名称',
      key: 'username',
      dataIndex: 'username',
    },
    {
      title: '用户角色',
      key: 'roleName',
      dataIndex: 'roleName',
    },
    {
      title: '手机号码',
      key: 'phone',
      dataIndex: 'phone',
    },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email'
    },
    {
      title: '账号状态',
      key: 'status',
      dataIndex: 'status',
      render: (text, record) => {
        const color = record.status === "0" ? "green" : "red";
        return (
          <Tag color={color} key={record.status}>
            {
              text === "0" ? "启用" : "禁用"
            }
          </Tag>
        );
      }
    },
    {
      title: '更新时间',
      key: 'upateTime',
      dataIndex: 'update_time',
      sorter: true,
      valueType: 'dateTime'
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  return (

    <PageContainer>

      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleAccountSysnc()}>
            账号同步
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({...params, sorter, filter})}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        expandable={{
          expandedRowRender: record =>
            <Row style={{textAlign: "center"}}>
              <Col span={24}>
                <Row>

                  <Col span={12} style={{marginBottom: "12px"}}>
                    <Row>
                      <Col span={6}>
                        <span>姓名：</span>
                      </Col>
                      <Col span={6}>
                        <Tag color="cyan" key={record.key}>
                          {record.username}
                        </Tag>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12} style={{marginBottom: "12px"}}>
                    <Row>
                      <Col span={6}>
                        <span>邮箱：</span>
                      </Col>
                      <Col span={6}>
                        <Tag color="cyan" key={record.key}>
                          {record.email}
                        </Tag>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12} style={{marginBottom: "12px"}}>
                    <Row>
                      <Col span={6}>
                        <span>手机号码：</span>
                      </Col>
                      <Col span={6}>
                        <Tag color="cyan" key={record.key}>
                          {record.phone}
                        </Tag>
                      </Col>
                    </Row>
                  </Col>
                  <Col span={12} style={{marginBottom: "12px"}}>
                    <Row>
                      <Col span={6}>
                        <span>描述：</span>
                      </Col>
                      <Col span={6}>
                        <Tag color="cyan" key={record.key}>
                          {record.description}
                        </Tag>
                      </Col>
                    </Row>
                  </Col>

                </Row>

              </Col>
            </Row>
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Button
            type="primary"
            danger
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}


      {stepFormValues && Object.keys(stepFormValues).length ? (
        <DetailsForm
          key='userModal'
          onSubmit={async value => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}

          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
          options={options}
        />
      ) : null}


    </PageContainer>
  );
};

export default TableList;
